import React from "react";
import localStorage from "store2";
import { useNavigate } from "react-router-dom";
import { createForm } from "@formily/core";
import { createSchemaField, ISchema } from "@formily/react";
import { UserInfoContext, UserInfoType } from "src/App";
import api from "src/http/api";

import { Form, FormItem, Input, Password, Submit } from "@formily/antd";
import { Card, Space, Typography } from "antd";
import LoginSvg from "src/public/imgs/login.svg";
import bgLeft from "src/public/imgs/bg-left.png";
import bgRight from "src/public/imgs/bg-right.png";

import globalStyles from "src/public/css/index.scss";
import styles from "./index.scss";

const { useContext } = React;

const Login: React.FC = () => {
  const context = useContext(UserInfoContext);
  const form = createForm();
  const navigate = useNavigate();

  const SchemaField = createSchemaField({
    components: {
      FormItem,
      Input,
      Password,
    },
  });

  const login = (param: object) => {
    api.login(param).then((res: any) => {
      localStorage.set("userInfo", res.data);
      context.setUserInfo(res.data as UserInfoType);
      navigate("/entity");
    });
  };

  const schema: ISchema = {
    type: "object",
    properties: {
      email: {
        type: "string",
        title: "邮箱",
        required: true,
        format: "email",
        "x-decorator": "FormItem",
        "x-component": "Input",
      },
      password: {
        type: "string",
        title: "密码",
        required: true,
        "x-decorator": "FormItem",
        "x-component": "Password",
      },
    },
  };

  return (
    <div
      className={`${(globalStyles as any).minHeight} ${(styles as any).root}`}
    >
      <div
        className={(globalStyles as any).bgLeft}
        style={{ backgroundImage: `url(${bgLeft})` }}
      />
      <div
        className={(globalStyles as any).bgRight}
        style={{ backgroundImage: `url(${bgRight})` }}
      />

      <div className={(globalStyles as any).verticallyCentered}>
        <Card className={(styles as any).card}>
          <Space>
            <div className={(styles as any).img}>
              <img
                src={LoginSvg}
                alt=""
                className={(globalStyles as any).verticallyCentered}
                style={{ width: 500 }}
              />
            </div>

            <Form
              form={form}
              layout="vertical"
              size="large"
              onAutoSubmit={login}
              style={{ width: 400, padding: 48 }}
            >
              <Typography.Title level={2}>登录</Typography.Title>
              <SchemaField schema={schema} />
              <Submit block size="large">
                登录
              </Submit>
            </Form>
          </Space>
        </Card>
      </div>
    </div>
  );
};

export default Login;
